package com.atguigu.java.ai.langchain4j.Config;

import com.atguigu.java.ai.langchain4j.store.MongoChatMemoryStore;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Configuration
public class XiaoxinAgentConfig {

    @Autowired
    private MongoChatMemoryStore mongoChatMemoryStore;

    @Autowired
    @Qualifier("webApplicationContext")
    private ResourceLoader resourceLoader;  // 注入Spring资源加载器

    @Bean
    ChatMemoryProvider chatMemoryProviderXiaozhi(){
        return memoryId -> MessageWindowChatMemory.builder()
                .id(memoryId)
                .maxMessages(20)
                .chatMemoryStore(mongoChatMemoryStore)
                .build();
    }

    @Bean
    ContentRetriever contentRetrieverXiaozhi() throws IOException {
        // 使用Spring资源加载器获取classpath下的资源
        Resource resource1 = resourceLoader.getResource("classpath:knowledge/医院信息.md");
        Resource resource2 = resourceLoader.getResource("classpath:knowledge/科室信息.md");
        Resource resource3 = resourceLoader.getResource("classpath:knowledge/神经内科.md");

        // 转换为文件系统路径并加载文档
        Document document1 = FileSystemDocumentLoader.loadDocument(getFilePath(resource1));
        Document document2 = FileSystemDocumentLoader.loadDocument(getFilePath(resource2));
        Document document3 = FileSystemDocumentLoader.loadDocument(getFilePath(resource3));

        List<Document> documents = Arrays.asList(document1, document2, document3);

        // 使用内存向量存储
        InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();

        // 摄入文档到嵌入存储
        EmbeddingStoreIngestor.ingest(documents, embeddingStore);

        // 创建并返回内容检索器
        return EmbeddingStoreContentRetriever.from(embeddingStore);
    }

    // 辅助方法：获取资源的文件路径
    private String getFilePath(Resource resource) throws IOException {
        // 对于开发环境（IDE中运行）
        if (resource.exists() && resource.isFile()) {
            return resource.getFile().getAbsolutePath();
        }
        // 对于打包后的JAR环境（可选实现）
        throw new IOException("资源不存在或无法访问: " + resource.getDescription());
    }
}
